package com.umeox.moto.watch.fitness.ui

import android.annotation.SuppressLint
import android.app.KeyguardManager
import android.content.Context.KEYGUARD_SERVICE
import android.content.Context.POWER_SERVICE
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.os.Handler
import android.os.PowerManager
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat.getSystemService
import com.umeox.moto.common.log.Logger
import com.umeox.moto.common.utils.SystemUtils
import com.umeox.moto.watch.fitness.R
import com.umeox.moto.watch.fitness.adapter.ChallengeAdapter
import com.umeox.moto.watch.fitness.base.BaseApp
import com.umeox.moto.watch.fitness.db.AppDatabase
import com.umeox.moto.watch.fitness.db.model.TodayChallenge
import com.umeox.moto.watch.fitness.utils.Utils
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import java.lang.invoke.MethodHandles.constant
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit

class  ChallengeTipActivity : ThemeAppCompatActivity() {

    private lateinit var mChallengeLevelDescTv: TextView
    private var mCurrentChallenge: TodayChallenge? = null
    private var isAuto: Boolean? = false

    private var wakeLock: PowerManager.WakeLock? = null
    private var kl: KeyguardManager.KeyguardLock? = null
    private var countDownTv: TextView? = null
    var recLen: Int = 0
    private var mHandler = Handler()

    private val finishCurrentAct = Runnable { finish() }
    private var executor: ScheduledExecutorService? = null


    @SuppressLint("DiscouragedApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val bundle = intent.extras
        val _id = bundle?.getLong(Utils.EXTRA_KEY_ID, 0) ?: 0
        isAuto = bundle?.getBoolean(Utils.EXTRA_KEY_AUTO)
        if (_id > 0) {
            mCurrentChallenge = AppDatabase.get().todayChallengeDao().queryById(_id)
        }
        if (mCurrentChallenge == null) {
            finish()
        }

        setContentView(R.layout.activity_challenge_tip)
        mChallengeLevelDescTv = findViewById(R.id.tv_challenge_desc)
        setChallengeDesc(mCurrentChallenge)
        val challengeLL = findViewById<LinearLayout>(R.id.ll_challenge)
        executor = Executors.newScheduledThreadPool(1)
        findViewById<View>(R.id.iv_start).setOnClickListener {

            challengeLL.removeAllViews()

            countDownTv = TextView(this@ChallengeTipActivity).apply {
                layoutParams = ViewGroup.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT
                )
                setTextColor(resources.getColor(R.color.light_navigationColor))
                textSize = 100f
                setTypeface(null, Typeface.BOLD)
                gravity = Gravity.CENTER

            }
            challengeLL.addView(countDownTv)

            val count = 3
            executor?.scheduleAtFixedRate(
                {

                    if (recLen == 3) {
                        executor?.shutdown()
                        val intent = Intent(this, ChallengeActivity::class.java)
                        intent.putExtra("challenge_data", mCurrentChallenge)
                        startActivity(intent)
                        finish()
                        return@scheduleAtFixedRate
                    }
                    val i = count - recLen

                    runOnUiThread {
                        countDownTv?.text = String.format(Locale.getDefault(),"%d",i)
                    }
                    recLen++

                },
                0,
                1000,
                TimeUnit.MILLISECONDS
            )


        }

        if (isAuto == true) {
            wakeUpAndUnlock()
            mHandler.postDelayed(finishCurrentAct, (30 * 1000).toLong())
        }
    }

    private fun setChallengeDesc(challengeBean: TodayChallenge?) {
        var challengeDescStr = resources.getString(R.string.walk_for_str)
        when (challengeBean?.sportType) {
            ChallengeAdapter.TYPE_WALK -> {
                challengeDescStr = resources.getString(R.string.walk_for_str)
            }
            ChallengeAdapter.TYPE_RUN -> {
                challengeDescStr = resources.getString(R.string.run_for_str)
            }
            ChallengeAdapter.TYPE_SWIM -> {
                challengeDescStr = resources.getString(R.string.swim_for_str)
            }
            ChallengeAdapter.TYPE_CYCLE -> {
                challengeDescStr = resources.getString(R.string.cycle_for_str)
            }
            ChallengeAdapter.TYPE_FOOTBALL -> {
                challengeDescStr = resources.getString(R.string.football_for_str)
            }
            ChallengeAdapter.TYPE_GYM -> {
                challengeDescStr = resources.getString(R.string.gym_for_str)
            }
            ChallengeAdapter.TYPE_JUMPROPE -> {
                challengeDescStr = resources.getString(R.string.jump_rope_for_str)
            }
            ChallengeAdapter.TYPE_YOGA -> {
                challengeDescStr = resources.getString(R.string.yoga_rope_for_str)
            }
        }
        mChallengeLevelDescTv.text =
            String.format(Locale.getDefault(), challengeDescStr, challengeBean?.duration)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        if (isAuto == true) {
            releaseLock()
        }
    }

    override fun onDestroy() {
        executor?.shutdown()
        if (isAuto == true) {
            releaseLock()
            BaseApp.getInstance().scheduleSportChallengeAlarm()
            mHandler.removeCallbacksAndMessages(null)
        }
        super.onDestroy()
    }


    private fun wakeUpAndUnlock() {
        if (kl == null) {
            val km = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
            kl = km.newKeyguardLock("unLock")
        }
        //解锁
        kl?.disableKeyguard()
        if (wakeLock == null) {
            val pm = getSystemService(POWER_SERVICE) as PowerManager
            wakeLock = pm.newWakeLock(
                PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.FULL_WAKE_LOCK,
                javaClass.simpleName
            )
        }
        // 点亮亮屏
        wakeLock?.acquire()
    }

    private fun releaseLock() {
        if (wakeLock != null) {
            try {
                wakeLock?.release()
            } catch (th: Throwable) {
                Logger.e("Releasing wakelock failed:$th")
            }
        } else {
            Logger.e("Wakelock reference is null")
        }
    }
}